/*
 * Copyright 2007 Robert Hanson <iamroberthanson AT gmail.com>
 * Copyright 2009 Matias Kruk <kruk.matias AT gmail.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.gwtsandbox.gears.orm.client;

import com.google.gwt.gears.client.Factory;
import com.google.gwt.gears.client.GearsException;
import com.google.gwt.gears.client.database.Database;
import com.google.gwt.gears.client.database.DatabaseException;

import java.util.HashMap;
import java.util.Map;

public abstract class GearsDataStore
{
    /**
     * Map holds a list of all currently open databases
     */
    protected static final Map dbMap = new HashMap();
    
    public abstract void createTable () throws DatabaseException;
    
    public abstract void deleteTable () throws DatabaseException;

    public abstract Object[] loadAll () throws DatabaseException;

    public abstract Object findById (Object id) throws DatabaseException;
    
//    public abstract Object[] findByExample (Object example) throws DatabaseException;
    public abstract GearsQuery getNamedQuery(String queryName) throws DatabaseException; 
    
    public abstract Object save (Object object) throws DatabaseException;
    
    public abstract void delete (Object object) throws DatabaseException;

    public abstract void close () throws DatabaseException;

    protected Database getDatabase(String namespace) 
    {
       if (!dbMap.containsKey(namespace))
       {
        	  Database db = Factory.getInstance().createDatabase();
        	  db.open(namespace);
              dbMap.put(namespace, db);
       }
       Database db = (Database) dbMap.get(namespace);
       return db;
    }
    
    protected void close(String namespace) throws DatabaseException
    {
        if(dbMap.containsKey(namespace))
        {
            Database db = (Database) dbMap.get(namespace);
            try
            {
               db.close();
            }
            finally
            {
               dbMap.remove(namespace);
            }
        }
    }
}
